package com.situ.mall.web.controller;


import com.alipay.api.AlipayApiException;

import com.alipay.api.internal.util.AlipaySignature;
import com.situ.mall.common.entity.OrderInfo;
import com.situ.mall.common.service.IOrderInfoService;
import com.situ.mall.common.service.IPayService;
import com.situ.mall.common.util.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private IPayService payService;

    @Autowired
    private AlipayConfig alipayConfig;

    @GetMapping("/payment")
    public String page2(Model model, Integer id) throws AlipayApiException {//model.addAttribute带数据到页面 thymeleaf渲染一下

        OrderInfo oi = orderInfoService.getById(id);

        model.addAttribute("orderInfo", oi);
        //带一个二维码
        String qrCode = payService.pay(id);
        model.addAttribute("qrCode", qrCode);

        return "payment";
    }

    @GetMapping
    public String page() {

        return "order";
    }

    @PostMapping("/save")
    public String save(Integer id,String ids, Integer addressId, Model model) {
        OrderInfo orderInfo;
        if(ids==""||ids==null){
            orderInfo = orderInfoService.saveOrder(id.toString(), addressId);
        }else {
            orderInfo = orderInfoService.saveOrder(ids, addressId);
        }
        model.addAttribute("payment", orderInfo);

        return "payment";
    }


    //接收支付宝返回的订单变更信息
    @PostMapping("/notify")
    @ResponseBody
    public String notify1(HttpServletRequest request) throws AlipayApiException {
        //获取支付宝POST过来反馈信息，将异步通知中收到的待验证所有参数都存放到map中
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
//调用SDK验证签名
//公钥验签示例代码
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getPublicKey(), "UTF-8", alipayConfig.getSignType());
//公钥证书验签示例代码
//   boolean flag = AlipaySignature.rsaCertCheckV1(params,alipayPublicCertPath,"UTF-8","RSA2");

        if (signVerified) {
            if (params.get("trade_success").equals("TRADE_SUCCESS")) {
                String code = params.get("out_trade_no");
                orderInfoService.paySuccess(code);
            }
            // TODO 验签成功后
            //按照支付结果异步通知中的描述，对支付结果中的业务内容进行1\2\3\4二次校验，校验成功后在response中返回success
        } else {
            // TODO 验签失败则记录异常日志，并在response中返回fail.
        }


        return "success";
    }

    @GetMapping("/status")
    @ResponseBody
    public String status(Integer id) {
        OrderInfo oi = orderInfoService.getById(id);
        return oi.getStatus();
    }

//    @JmsListener(destination = "aaa")//监听aaa这个队列来消费，如果15分钟还是未支付，改成已取消
    public void orderCheck(Integer id) {
        OrderInfo oi = orderInfoService.getById(id);
        if (oi.getStatus().equals("0")) {
            orderInfoService.updateOrderStatus(id);
        }
    }


}
